package kwic.pf;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.util.StringTokenizer;

public class TransformFilter extends Filter {

	public TransformFilter(Pipe input, Pipe output) {
		super(input, output);
	}

	@Override
	protected void transform() {
		try {
			CharArrayWriter writer = new CharArrayWriter();

			int c = input_.read();
			while (c != -1) {
				if (((char) c) == '\n') {
					String line = writer.toString();
					StringTokenizer tokenizer = new StringTokenizer(line);
					StringBuffer sbuf = new StringBuffer();
					boolean isFirst = true;
					while (tokenizer.hasMoreTokens()) {
						if (isFirst) {
							isFirst = false;
							sbuf.append(tokenizer.nextToken().toUpperCase());
							sbuf.append(' ');
						} else {
							sbuf.append(tokenizer.nextToken());
							sbuf.append(' ');
						}
					}
					sbuf.append('\n');
					char[] chars = sbuf.toString().toCharArray();
					for (int i = 0; i < chars.length; i++) {
						output_.write(chars[i]);
					}
					writer.reset();
				} else {
					writer.write(c);
				}

				c = input_.read();
			}

			output_.closeWriter();
		} catch (IOException exc) {
			exc.printStackTrace();
			System.err.println("KWIC Error: Could not transform the data.");
			System.exit(1);
		}
	}

}
